package com.xr.blog.controller;

import com.xr.blog.tools.Base64;
import com.xr.blog.tools.IdUtils;
import com.xr.blog.tools.Result;
import com.xr.blog.tools.authimage.VerifyCodeUtils;
import com.xr.blog.tools.constant.Code;
import com.xr.blog.tools.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author 幸仁杰
 */
@RestController
@RequestMapping("/squirrelblog")
public class CaptchaController {
    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Result getCode(HttpServletResponse response) throws IOException {
        // 生成随机字串（验证码内容）
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        //要缓存进redis的验证码key，此key由验证码标识符+uuid组成，用户登录时使用此key从缓存获取验证码内容比较
        String verifyKey = Code.CAPTCHA_CODE_KEY + uuid;

        //进行缓存
        redisCache.setCacheObject(verifyKey, verifyCode, Code.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 生成图片
        int w = 125, h = 52;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);

        try {
            Map map=new HashMap<>();
            map.put("uuid", uuid);
            map.put("img", Base64.encode(stream.toByteArray()));
            return Result.of(Code.SC_OK.getState(),Code.SC_OK.getDescription(),map);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.of(Code.SC_INTERNAL_SERVER_ERROR.getState(),Code.SC_INTERNAL_SERVER_ERROR.getDescription(),e.getMessage());
        }
        finally
        {
            stream.close();
        }
    }
}
